package com.junxonline.instant.common.util.api;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.junxonline.instant.common.constant.TerminalInfoConstant;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Token工具类
 *
 * @author JunX
 * @date 2021-09-15
 */
@Data
@Component
public class TokenUtils {

    /**
     * token过期时间（ms）
     */
    @Value("${auth.tokenExpireTime}")
    private Long tokenExpireTime;

    /**
     * 签发Token
     *
     * @param terminalCode 终端编号
     * @param currentTime  签发时间
     * @return String
     */
    public String sign(String terminalCode, Long currentTime) {
        String token = null;
        try {
            Date expireAt = new Date(currentTime + tokenExpireTime);
            token = JWT
                    .create()
                    .withClaim(TerminalInfoConstant.KEY_TERMINAL_CODE, terminalCode)
                    .withClaim(TerminalInfoConstant.KEY_SIGN_TIME, currentTime)
                    .withExpiresAt(expireAt)
                    // 加密盐
                    .sign(Algorithm.HMAC256(terminalCode));
        } catch (IllegalArgumentException | JWTCreationException e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 校验token
     *
     * @param token token
     * @param terminalCode 终端编号
     * @return boolean
     */
    public boolean verify(String token, String terminalCode) {
        if (StrUtil.isBlank(terminalCode)) {
            return false;
        }
        try {
            JWTVerifier jwtVerifier = JWT
                    // 解密盐
                    .require(Algorithm.HMAC256(terminalCode))
                    .build();
            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取终端编号
     *
     * @param token token
     * @return terminalCode
     */
    public String getTerminalCode(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim(TerminalInfoConstant.KEY_TERMINAL_CODE).asString();
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从token中获取签发时间
     *
     * @param token token
     * @return signTime
     */
    public Long getSignTime(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim(TerminalInfoConstant.KEY_SIGN_TIME).asLong();
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return null;
    }

}
